package org.hbbTlias2025.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.hbbTlias2025.utils.CurrentHolder;
import org.hbbTlias2025.utils.JwtUtil;

import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        获取的请求路径
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")){
            log.info("登录请求,直接放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader("token");
        log.info("token就是如下的内容{}",token);


        if(token == null || token.isEmpty()){
            log.info("token为空,请直接登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            Claims claims =  JwtUtil.parseToken(token);
            Integer id =  Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(id);
            log.info("当前员工id为：{}，将其存入thread local中", id);

        } catch (Exception e) {
            log.info("token非法,请爬爬开");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("令牌合法,请直接登录");
        filterChain.doFilter(servletRequest,servletResponse);
        CurrentHolder.remove();



        return;


    }
}
